/**
 * 共有逻辑的处理与接口
 */

var testOnly = false;

// 本游戏的最大注单数
var _maxBetCount = 0;
function checkBetCount(count) {
    // 注单数没有限制
    if (_maxBetCount == 0) return true;
    var curr = Lottery.totalCount(Lottery.curr());
    if (curr + count <= _maxBetCount) return true;

    var t = Math.max(0, _maxBetCount - curr);
    alert2("下注单数超过上限，投注失败！<br/>当前还可以下注：" + t + "注！", true);
    return false;
}

/**
 * 初始化公告的逻辑
 */
function initCommon() {
}

/**
 * 初始化游戏页面
 */
function initGame(game, cb, first) {
    if (first === undefined) first = true;
    var register_tab_index = function(tab, index) {
        tab.click(function() {
            $('.am-tabs').tabs('open', index);
        })
    }
    if (first) {
        var arr = $(".zy-tabs li");
        for (var i = 0; i < arr.length; i++) register_tab_index($(arr[i]), i);

        // 填入筹码输入框
        scan_counter_confirm();
    }
            
    // 回调填充内容
    cb();
    scan_bet_items();
    refresh_bet_items();
}

/**
 * 切换游戏
 */
function switchGame(game, cb) {
    window.notBetUI = false;
    window.game = game;
    window.gameRule = Util.getGameRule(game);
    urlInfo.params.game = game;
    $("#header_game_name").html(get_game_display_name(game));
    $("#page_game_name").html(get_game_display_name(game));
    $("#title span").html(get_game_display_name(game));
    $(".logo div").html(get_game_display_name(game));
    $("#total_sum_money").html("(0.00)");
    GameList.draw();
    Util.setGame(game);

    // 开奖结果相关
    Result.switchGame(game);
    Result.refresh_curr();
    Result.cb();

    // 刷新赔率
    Lottery.switchGame(game);
    Lottery.refresh_rate();

    $("#stat_play_ctn2").hide();
    $("#kjtz-ctn").hide();
    _loadGameBetPage();

    // 延迟获取下本彩种输赢信息
    if (context.center.meTimer) {
        clearTimeout(context.center.meTimer);
    }
    context.center.meTimer = setTimeout(function() {
        ME.query();
    }, 1500);

    // 延迟刷新历史开奖列表
    if (context.center.resultListTimer) {
        clearTimeout(context.center.resultListTimer);
    }
    context.center.resultListTimer = setTimeout(function() {
        Result.refresh_list();
    }, 2000);
}

/**
 * 当前是否可以下注
 */
function can_bet() {
    var c = Result.curr();
    if (!c || !isEmpty(c.red)) return false;
    if (c.end/1000 - get_server_time() <= 0) return false;
    return true;
}

/**
 * 设置最近一期的开奖结果
 * name为第几期, list为结果列表，例如：
 * set_lastest_result("165230", [3, 3, 2, 1, 5, 6, 7, 8, 9, 10])
 */
function set_lastest_result(name, list, useNumber) {
    $("#cur_turn_num").html((name || "--") + " ");

    $("#result_balls").empty();
    if (!window.game) return;
    var f = context.global.game[game].drawResult;
    if (list && f)
        list = f(list);
}

/**
 * 开启倒计时，单位为秒
 * 分别为开奖倒计时和封盘倒计时
 */
function set_countdown(openTime, closeTime, issue, betEnable) {
    betEnable = betEnable === undefined ? true : betEnable;
    if (timer)  {
        clearTimeout(timer);
        timer = 0;
    }
    if (!issue) {
        $("#next_turn_num").html("--");
        $("#bet-date").html("00:00");
        $("#open-date").html("00:00");
        on_fengpan();
        return;
    }

    start = new Date().getTime()/1000;
    var f = function() {
        var delta = new Date().getTime()/1000 - start;
        var t = openTime - delta;
        if (t < 0 || !t) t = 0;
        if (t > 24 * 3600) {
            // 超过一天
            var day = parseInt(t / (24 * 3600));
            t = t - day * 24 * 3600;
            var hour = parseInt(t / 3600);
            if (hour < 10) hour = "0" + hour;
            t = t % 3600;
            var min = parseInt(t / 60);
            if (min < 10) min = "0" + min;
            t = Math.ceil(t % 60);
            if (t < 10) t = "0" + t;
            $("#open-date").html(day + '天 ' + (hour) + ":" + min + ":" + t);
        }
        else if (t >= 3600) {
            var hour = parseInt(t / 3600);
            if (hour < 10) hour = "0" + hour;
            t = t % 3600;
            var min = parseInt(t / 60);
            if (min < 10) min = "0" + min;
            t = Math.ceil(t % 60);
            if (t < 10) t = "0" + t;
            $("#open-date").html((hour) + ":" + min + ":" + t);
        }
        else if (t <= 0) {
            $("#open-date").html('获取下一期');
        }
        else {
            var i1 = parseInt(t / 60), i2 = Math.ceil(t % 60);
            $("#open-date").html((i1 < 10 ? "0" + i1 : i1) + ":" + (i2 < 10 ? "0" + i2 : i2));
        }

        t = closeTime - delta;
        if (t < 0 || !t) t = 0;
        if (t > 24 * 3600) {
            // 超过一天
            var day = parseInt(t / (24 * 3600));
            t = t - day * 24 * 3600;
            var hour = parseInt(t / 3600);
            if (hour < 10) hour = "0" + hour;
            t = t % 3600;
            var min = parseInt(t / 60);
            if (min < 10) min = "0" + min;
            t = Math.ceil(t % 60);
            if (t < 10) t = "0" + t;
            $("#bet-date").html(day + '天 ' + (hour) + ":" + min + ":" + t);
        }
        else if (t >= 3600) {
            var hour = parseInt(t / 3600);
            if (hour < 10) hour = "0" + hour;
            t = t % 3600;
            var min = parseInt(t / 60);
            if (min < 10) min = "0" + min;
            t = Math.ceil(t % 60);
            if (t < 10) t = "0" + t;
            $("#bet-date").html((hour) + ":" + min + ":" + t);
        }
        else {
            var i1 = parseInt(t / 60), i2 = Math.ceil(t % 60);
            $("#bet-date").html((i1 < 10 ? "0" + i1 : i1) + ":" + (i2 < 10 ? "0" + i2 : i2));
        }

        if (t == 0 || !betEnable) on_fengpan();
        else on_kaipan();
    };
    f();
    timer = setInterval(f, 200);

    // 第几期
    $("#next_turn_num").html(issue)
}
var timer, start;

/**
 * 设置账户信息，参数分别为：账号名称、余额、未结算金额
 * 如果传递undefined，则表示没有变化
 */
function set_account_info(name, money, betMoney) {
    if (name !== undefined)
        $("#userinfo_name").html(name);
    if (money !== undefined)
        $("#userinfo_money").html(money/100 + "");
    if (betMoney !== undefined)
        $("#userinfo_unbalancedMoney").html(betMoney/100 + "");
}

/**
 * 设置长龙的信息，参数list为数组，如
 * [
 *     { name: '冠亚大', value: 6 },
 *     ...
 * ]
 */
function set_long_queue(list) {
    var div = $("#stat_play_ctn");
    div.empty();

    // 标题
    div.append('<table class="u-table2">' +
               '  <thead> ' +
               '    <tr> ' +
               '      <th id="stat_play_list_desc">长龙排行榜</th> ' +
               '    </tr> ' +
               '  </thead> ' +
               '</table>');

    var table = $("<table class='u-table5'></table>");
    var tbody = $('<tbody id="stat_play_list"></tbody>');
    table.append(tbody);
    div.append(table);

    var index = 1;
    for (var i in list) {
        var o = list[i];
        var k, v;
        for (var j in o) {
            k = j;
            v = o[j];
        }
        var tr = $("<tr class='u-tb5-tr__index__'></tr>".replace(/__index__/, index));
        tr.append("<th>" + k + "</th>");
        tr.append("<td class='statFont'>" + v + "期</td>");
        tbody.append(tr);
        index = index == 1 ? 2 : 1;
    }
    if (list.length == 0) {
        div.hide();
    }
    else div.show();
}

/**
 * 设置投注的历史信息，参数list为数组，如：
 * [{ name: "冠军 大", odds: 1.99, total: 2000  }, ...]
 * 
 */
function set_bet_history(list) {
    $("#user-bet-list").empty();
    if (list.length == 0) {
        $("#lastBets-title").hide();
        return;
    }
    $("#lastBets-title").show();

    var l = '<li><p>期号：<span class="bid">__issue__</span></p>' +
            '    <p>内容：<span class="text5">__title__  </span>@ <span class="odds">__rate__</span></p>' +
            '    <p>金额：￥__v__</p>' +
            '</li>';
    for (var i in list) {
        var o = list[i];
        var li = l.replace(/__issue__/, Lottery.curr());
        li = li.replace(/__title__/, o.name);
        li = li.replace(/__rate__/, o.odds);
        li = li.replace(/__v__/, o.total/100);
        $("#user-bet-list").append(li);
    }
}

/**
 * 弹出提示框
 */
alert2 = function(message, warning) {
    warning = warning === undefined ? true : warning;
    layer.alert(message, {
        icon: warning ? 2 : 1,
    });
}
closeAlert = function() {
    $("#clue").modal("close");
}

/**
 * 弹出Loading框
 */
function startLoading() {
    $("#loading").modal({
    });
}
function stopLoading() {
    $("#loading").modal("close");
}

/**
 * 跳转到个人中心
 */
function switchCenter(n1, n2, params) {
    params = params || {};
    if (n1) params.n1 = n1;
    if (n2) params.n2 = n2;
    params.file = 'center.html';
    return Util.genUrl(params);
}

// 刷新本期投注信息
function refresh_curr_bet_list() {
    var bets = context.bets[game] || {};
    var issue = Lottery.curr() || "";
    bets = bets[issue] || [];

    // 对同一组的信息做下合并
    var data = Lottery.combineGroup(bets);

    var list = [];
    for (var k in data) {
        var o = data[k];
        if (o.group) {
            k = o.group.split("_")[0];
        }
        else k = gameRule.getTargetName(o.target);

        list.push({
            name: k,
            odds: o.rate,
            total: o.amount
        });
    }
    set_bet_history(list);
}

// 显示某期的盈利结果
function show_profit_view(type, issue, result) {
    $("#popup .title img").attr("src", "../public/all/images/title-result.png");
    Lottery.today(function(r) {
        switch_page("profit", $('#popup_content'), function() {
            // 填充数据
            $(".profit-view .issue").html(issue + "期");
            $(".profit-view .total").html(result.amount/100);
            $(".profit-view .profit").html(result.profit/100);
        });
        $("#popup").modal({
            width:1024,
        });
    });
}

/**
 * 显示中奖提示框
 */
function show_bonus_clue(list) {
    Message.showRight(null, list);
}

// 配置url
context.config.page_url = urlInfo.protocol + "://" + urlInfo.host + (urlInfo.path.replace(urlInfo.file, "")) + "pages/";
context.config.center = urlInfo.protocol + "://" + urlInfo.host + (urlInfo.path.replace(urlInfo.file, "")) + "center.html";

// 调整左边栏的高度，确保覆盖整个屏幕
setInterval(function() {
    var v = $(window).height() - 166;
    $(".ag-left .siderbar").css("min-height", (v) + "px");
}, 40);
